import globalVisionEntertainment.nba.Database;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.swing.*;
import javax.swing.table.TableColumnModel;

public class MainFrame extends SheetFrame implements WindowListener, ActionListener
{
	static
	{
		try
		{
			Class.forName("com.mysql.jdbc.Driver");
		}
		catch (ClassNotFoundException e)
		{
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			System.exit(ERROR);
		}
	}

	// JPopupMenu contextMenu;
	private final JButton showButton;
	private final JSpinner averageRangeSpinner;

	public MainFrame()
	{
		super(true);

		setTitle("Player Statistics Viewer");
		setSize(500, 400);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		// contextMenu = new JPopupMenu();
		// addPopup(table, contextMenu);

		JPanel panel = new JPanel();
		panel.setLayout(new BorderLayout());

		panel.add(new JScrollPane(table), BorderLayout.CENTER);

		JPanel panel2 = new JPanel();
		panel2.setLayout(new FlowLayout());

		showButton = new JButton("Show");
		showButton.addActionListener(this);
		panel2.add(showButton);
		panel2.add(new JLabel("average for last"));
		averageRangeSpinner = new JSpinner(new SpinnerNumberModel());

		averageRangeSpinner.setPreferredSize(new Dimension(50, 30));
		averageRangeSpinner.setValue(10);
		panel2.add(averageRangeSpinner);
		panel2.add(new JLabel("games"));

		panel.add(panel2, BorderLayout.SOUTH);

		getContentPane().add(panel);

		this.addWindowListener(this);

		// getContentPane().add(table);
	}

	@Override
	protected void loadData() throws IOException
	{
		Connection conn = null;
		try
		{
			conn = Database.getConnection();
			String sql = "SELECT * FROM NBA.`player stat total` order by `date` desc limit 0,500;";

			Statement statement = conn.createStatement();
			statement.execute(sql);

			ResultSet resultSet = statement.getResultSet();
			ResultSetMetaData metaData = resultSet.getMetaData();

			int columnCount = metaData.getColumnCount();
			tableModel.addColumn("");

			TableColumnModel columnModel = table.getColumnModel();

			List<String> hidedColumns = Arrays.asList(Settings.getHidedColumns());

			for (int i = 1; i <= columnCount; i++)
			{
				String columnLabel = metaData.getColumnLabel(i);
				System.out.println(columnLabel);

				if (hidedColumns.contains(columnLabel) == false)
					tableModel.addColumn(columnLabel);

				// columnModel.getColumn(i).setPreferredWidth(ColumnWidth.getWidth(columnLabel));
			}

			resultSet.first();

			do
			{

				ArrayList<Object> rowData = new ArrayList();
				rowData.add(false);
				for (int i = 0; i < columnCount; i++)
				{
					String columnLabel = metaData.getColumnLabel(i + 1);
					System.out.println(columnLabel);

					if (hidedColumns.contains(columnLabel) == false)
						rowData.add(resultSet.getString(i + 1));
				}
				tableModel.addRow(rowData.toArray());

			} while (resultSet.next());
		}
		catch (SQLException e)
		{
			JOptionPane.showMessageDialog(this, "Error in connecting to database or reading data from database.\n" + "Is MySql running?", "Database Error",
					JOptionPane.ERROR_MESSAGE);
			System.exit(ERROR);
		}
		finally
		{
			try
			{
				if (conn != null)
					conn.close();
			}
			catch (SQLException e)
			{
				// TODO ×Ô¶¯Éú³ÉµÄ catch ¿é
				e.printStackTrace();
			}
		}
	}

	@Override
	public void windowClosing(WindowEvent e)
	{
		TableColumnModel columnModel = table.getColumnModel();
		for (int i = 0; i < columnModel.getColumnCount(); i++)
		{
			String label = tableModel.getColumnName(i);
			ColumnWidth.setWidth(label, columnModel.getColumn(i).getWidth());
		}

		try
		{
			ColumnWidth.write();
		}
		catch (IOException e1)
		{
			JOptionPane.showMessageDialog(this, "Error in saving column width\n+" + e1.getMessage());
		}
		try
		{
			Settings.save();
		}
		catch (IOException e1)
		{
			// TODO 自动生成的 catch 块
			e1.printStackTrace();
		}
	}

	// @formatter:off
	@Override
	public void windowClosed(WindowEvent e)
	{
	}

	@Override
	public void windowIconified(WindowEvent e)
	{
	}

	@Override
	public void windowDeiconified(WindowEvent e)
	{
	}

	@Override
	public void windowActivated(WindowEvent e)
	{
	}

	@Override
	public void windowDeactivated(WindowEvent e)
	{
	}

	// @formatter:on

	@Override
	public void actionPerformed(ActionEvent e)
	{
		assert e.getSource() == showButton;

		ArrayList<String> list = new ArrayList<String>();
		for (int i = 0; i < tableModel.getRowCount(); i++)
		{
			if (tableModel.getValueAt(i, 0).equals(true))
			{
				list.add((String) tableModel.getValueAt(i, 1));
				System.out.println(tableModel.getValueAt(i, 1));
			}
		}

		String[] playerNames = new String[list.size()];
		list.toArray(playerNames);

		AverageFrame f = new AverageFrame(playerNames, (int) averageRangeSpinner.getValue(), getWidth());
		f.setVisible(true);

	}

}
